package com.wjw.cloud.util;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.wjw.cloud.common.api.CommonResult;
import com.wjw.cloud.common.service.RedisService;
import com.wjw.cloud.controller.KaptchaController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

@Component
public class KaptchaUtil {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisService redisService;

    private static Logger logger = LoggerFactory.getLogger(KaptchaController.class);

    public void createImageCode(HttpServletRequest request, HttpServletResponse response) {

        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

        try {
            // 生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute("imageCode", createText);

            // 把验证码保存到 redis 里面
            redisService.set("imageCode", createText, 360L);

            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);

            logger.info("createImageCode:{}", request.getSession().getAttribute("imageCode"));
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        ServletOutputStream responseOutputStream = null;

        try {
            responseOutputStream = response.getOutputStream();
            responseOutputStream.write(captchaChallengeAsJpeg);
            responseOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (responseOutputStream != null) {
                try {
                    responseOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public CommonResult checkCode(@RequestBody Map<String, Object> map) {

        String imageCode = String.valueOf(redisService.get("imageCode"));

        if ("".equals(imageCode) || "".equals(map.get("code"))) {

            return CommonResult.failed("验证码为空，请刷新页面后重试！");

        }

        if (Objects.equals(imageCode, map.get("code"))) {

            return CommonResult.success(null);

        } else {

            return CommonResult.failed("验证码不匹配，请重新输入！");

        }

    }

}
